<template>
    <div class="mobilelogin">
        <el-dialog title='手机验证码登陆' :style="{height: '100%'}" :visible.sync="display" @close="close_mobilelogin"
               width="35%" :close-on-click-modal='false' :modal="true">
            <span>
                <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px"
                         class="demo-ruleForm">
                    <el-form-item prop="user" label-width="5%">
                        <el-input type="text" v-model="ruleForm.user" autocomplete="off"
                                  clearable prefix-icon="el-icon-user"
                                  placeholder="请输入手机号或邮箱" :style="{marginTop: '10px',width: '95%',height: '30px'}">
                        </el-input>
                    </el-form-item>
                    <el-form-item prop="code" label-width="5%">
                        <el-input type="text" autocomplete="off" v-model="ruleForm.code" clearable
                                  prefix-icon="el-icon-chat-line-round"
                                  placeholder="请输入收到的验证码" :style="{marginTop: '10px',width: '95%',height: '30px'}">
                            <template slot="append">
                                <span class="sms" @click="send_sms">{{ sms_interval }}</span>
                            </template>
                        </el-input>
                    </el-form-item>

                    <el-form-item label-width="10%">
                        <el-button type="warning" @click="submitForm('ruleForm')"
                                   :style="{width: '90%', height: '45px', marginTop: '20px',fontSize: '16px'}">登陆</el-button>
                    </el-form-item>
                </el-form>
            </span>
            <span slot="footer" class="dialog-footer">
                <el-button :style="{marginRight: '27%',border: '0px'}" @click="go_dialog('register')">注册</el-button>
                <el-button :style="{border: '0px'}" @click="go_dialog('login')">账号密码登陆</el-button>
                <el-button :style="{border: '0px'}" @click="go_dialog('thirdLogin')">其他方式登陆</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
    export default {
        name: "MobileLogin",
        data(){
            // 校验用户
            var validateUser = (rule, value, callback) => {
                var phoneReg = /(^1[3-9][0-9]{9}$)/;
                if (value === '') {
                    callback(new Error('请输入手机号'));
                }
                // 判断手机号码格式
                if (!phoneReg.test(value)) {
                    callback(new Error('手机号码格式错误'));
                }
                // 如果没有错误就可以回调
                callback();
            };
            // 校验验证码
            var validateCode = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入验证码'));
                }
                // 如果没有错误就可以回调
                callback();
            };
            return{
                display: true,
                // 表单数据
                ruleForm: {
                    user: "",
                    code: "",
                },
                // 登陆校验
                rules: {
                    user: [
                        {validator: validateUser, trigger: 'blur'}
                    ],
                    code: [
                        {validator: validateCode, trigger: 'blur'}
                    ],
                },
                // 验证码框尾部显示
                sms_interval: '获取验证码',
                // 是否发送了验证码
                is_send: false,
            }
        },
        methods:{
            // 关闭登陆框
            close_mobilelogin(){
                // 子组件向父组件传参
                this.$emit('close')
            },
            // 跳转组件
            go_dialog(dialog){
                console.log(dialog);
                this.$emit("go", dialog)
            },

            // 提交表单
            submitForm(formName) {
                // 进行校验
                this.$refs[formName].validate((valid) => {
                    // 判断校验结果，布尔值
                    if (valid) {
                        const loading = this.$loading({
                            lock: true,
                            text: '正在登陆...',
                            spinner: 'el-icon-loading',
                            background: 'rgba(0, 0, 0, 0.7)'
                        });
                        // 更改显示层级
                        $(".el-loading-mask").css("z-index", "8888");
                        setTimeout(() => {
                            this.$axios({
                                url: this.$settings.base_url + "/user/login/mobile",
                                method: "post",
                                data: {
                                    "mobile": this.ruleForm.user,
                                    "code": this.ruleForm.code
                                }
                            }).then(response => {
                                console.log(response.data);
                                // 正确
                                if (!response.data.status) {
                                    let token = response.data["results"]["token"];
                                    if (token) {
                                        this.$cookies.set("token", token);
                                        let user_info = response.data["results"]["user_info"];
                                        this.$cookies.set("user_info", user_info);
                                        console.log(this.$cookies.get("user_info"));
                                        // 放到vuex中
                                        this.$store.state.userinfo = user_info;
                                        this.$store.state.token = token;
                                        loading.close()
                                    }
                                    // 子组件向父组件传参
                                    this.$emit('close')
                                }
                                // 错误
                                else {
                                    loading.close()
                                    // 更改显示层级
                                    this.$message({
                                        message: response.data.msg,
                                        type: 'error',
                                        duration: 2000,
                                        onClose: () => {
                                            this.ruleForm.user = '';
                                            this.ruleForm.pass = '';
                                        }
                                    });
                                    $(".el-message--error").css("z-index", "8888");
                                }
                            }).catch(response => {
                                loading.close()
                                // 更改显示层级
                                this.$message({
                                    message: "登陆失败",
                                    type: 'error',
                                    duration: 2000,
                                    onClose: () => {
                                        this.ruleForm.user = '';
                                        this.ruleForm.code = '';
                                    }
                                });
                                $(".el-message--error").css("z-index", "8888");
                            });
                        }, 1000);
                    }
                });
            },
            // 发送验证码
            send_sms() {
                // 判断是否发送了验证码
                if (this.is_send) return;  // 发送了就直接返回
                this.is_send = true; // 切换发送状态为已经发送
                this.sms_interval = "发送中...";
                this.$axios({
                    url: this.$settings.base_url + "/user/sms",
                    method: "post",
                    data: {
                        mobile: this.ruleForm.user
                    }
                    // 回调成功
                }).then(response => {
                    // 判断数据状态码
                    if (response.data.status !== 0) {
                        this.sms_interval = "发送失败";
                        this.$message({
                            message: response.data.msg,
                            type: 'error',
                            duration: 2000,
                            onClose: () => {
                                this.ruleForm.reg_mobile = '';
                                this.sms_interval = "获取验证码";
                                this.is_send = false; // 重新恢复点击发送功能的条件
                            }
                        });
                        $(".el-message--error").css("z-index", "8888");
                    } else { // 发送验证码成功的逻辑

                        // 验证码发送成功，开始倒计时
                        let sms_interval_time = 60;

                        let timer = setInterval(() => {
                            if (sms_interval_time <= 1) {
                                clearInterval(timer);
                                this.sms_interval = "获取验证码";
                                this.is_send = false; // 重新恢复点击发送功能的条件
                            } else {
                                sms_interval_time -= 1;
                                this.sms_interval = `${sms_interval_time}秒后再发`;
                            }
                        }, 1000);
                    }

                }).catch(() => {
                    this.sms_interval = "发送过快";
                    this.$message({
                        message: "验证码发送发送频率过快",
                        type: 'error',
                        duration: 2000,
                        onClose: () => {
                            this.sms_interval = "获取验证码";
                            this.is_send = false; // 重新恢复点击发送功能的条件
                        }
                    });
                    $(".el-message--error").css("z-index", "8888");
                })

            },
        }
    }
</script>

<style scoped>
    .sms {
        color: orange;
        cursor: pointer;
        display: inline-block;
        width: 100px;
        text-align: center;
        user-select: none;
    }
</style>